package com.cgx.tablet.beeper.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;

import com.cgx.tablet.beeper.MyApplication;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImgUtils {

    public static String getRealUrl(String url) {
        if (TextUtils.isEmpty(url))
            return "";
        if (!url.startsWith("http"))
            url = MyApplication.PHOTO_BASE_URL + url;
        return url.replaceAll("amp;", "");
    }

    /**
     * 缩放
     *
     * @param realImage    图片
     * @param maxImageSize 最大的宽度或者高度
     * @param filter       是否过滤
     */
    public static Bitmap scaleDown(Bitmap realImage, float maxImageSize, boolean filter) {
        float ratio = Math.min(maxImageSize / realImage.getWidth(),
                maxImageSize / realImage.getHeight());
        int width = Math.round(ratio * realImage.getWidth());
        int height = Math.round(ratio * realImage.getHeight());
        return Bitmap.createScaledBitmap(realImage, width, height, filter);
    }

    //压缩方法
    public static byte[] compressBitmap(Bitmap bmp) {
        int imgWidth = bmp.getWidth();
//        int imgHeight = bmp.getHeight();
//        Log.i("BTCODE", "IMG is "+imgWidth+" X "+imgHeight+"px");
        float imgMaxWidth = 1440;
        if (imgWidth > imgMaxWidth) {
            bmp = scaleDown(bmp, imgMaxWidth, true);
//             Log.i("BTCODE", "IMG is "+bmp.getWidth()+" X "+bmp.getHeight()+"px");
        }
        /** 从100开始，表示一开始不压缩。因为有些图片一开始就很小就不需要压缩 */
        int options = 100;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap temBitmap = Bitmap.createBitmap(bmp);
        ByteArrayOutputStream temBaos = new ByteArrayOutputStream();
        temBitmap.compress(Bitmap.CompressFormat.JPEG, options, temBaos);
        int temSizeinKB = temBaos.toByteArray().length / 1024;
//         Log.i("BTCODE", "tem file KB size is now: " + temSizeinKB + "KB");
        while (temSizeinKB > 200 && options >= 60) {
//            Log.i("BTCODE", "compressed tem");
            baos.reset();
            temBaos.reset();
            options -= 10;
            temBitmap.compress(Bitmap.CompressFormat.JPEG, options, temBaos);
            temSizeinKB = temBaos.toByteArray().length / 1024;
//            Log.i("BTCODE", "tem file after 1 compress KB size is now: " + temSizeinKB + "KB");
        }
//        Log.i("BTCODE", "trying now, quality is: "+options);
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
//        Log.i("BTCODE", "compressed real bitmap, size is: "+baos.toByteArray().length/1024+"KB");
        return baos.toByteArray();
    }

    /**
     * 等比压缩
     *
     * @param bmp 原始的Bitmap
     * @return Base64
     */
    public static String bitmap2Base64(Bitmap bmp) {
        return Base64.encodeToString(compressBitmap(bmp), Base64.DEFAULT);
    }

    public static String createImgPathInAppFolder(Context context, String folderName, String fileName) {
        String filePath;
        File file;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            file = new File(Environment.getExternalStorageDirectory() + "/LED/");
            if (file.exists() || file.mkdirs()) {
                filePath = Environment.getExternalStorageDirectory() + folderName;
                file = new File(filePath);
                if (file.exists() || file.mkdirs()) {
                    filePath = filePath + "/" + fileName;
                    return filePath;
                }
            }
        } else {
            filePath = context.getFilesDir() + folderName;
            file = new File(filePath);
            if (file.exists() || file.mkdirs()) {
                filePath = filePath + "/" + fileName;
                return filePath;
            }
        }
        return "";
    }

    public static boolean saveBitmapToLocal(Bitmap bmp, String filePath) {
        try {
            FileOutputStream fos;
            fos = new FileOutputStream(new File(filePath));
            fos.write(compressBitmap(bmp));
            fos.flush();
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static Drawable imgPathToDrawable(Context context, String imgPath) {
        return new BitmapDrawable(context.getResources(), imgPath);
    }

    /**
     * 转换成圆形
     *
     * @param source 原图
     * @return 圆形Bitmap
     */
    public static Bitmap transToRound(Bitmap source) {
        int size = Math.min(source.getWidth(), source.getHeight());
        int width = (source.getWidth() - size) / 2;
        int height = (source.getHeight() - size) / 2;
        Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader =
                new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        if (width != 0 || height != 0) {
            // source isn't square, move viewport to center
            Matrix matrix = new Matrix();
            matrix.setTranslate(-width, -height);
            shader.setLocalMatrix(matrix);
        }
        paint.setShader(shader);
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return bitmap;
    }

    //根据需求的宽高获取 inSampleSize
    public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,
                                           int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;

        int inSampleSize = 1;

        if (width > reqWidth || height > reqHeight) {
            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(height * 1.0f / reqHeight);

            inSampleSize = Math.max(widthRadio, heightRadio);
        }

        return inSampleSize;
    }

}
